﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonExtensions.StringExtensions;
using DBMigrator.Core.DbObjects.ForeignKey;
using StructureMap;

namespace DBMigrator.Core.DbObjects.Column
{
    public class ChangeColumn : IChangeColumn
    {
        public Type SqlGenerationType
        {
            get { return typeof(IChangeColumn); }
        }

        public string CurrentName { get; private set; }
        public string NewName { get; private set; }
        public Type NewType { get; private set; }
        public uint NewLength { get; private set; }
        public IAddForeignKey NewForeignKey { get; private set; }

        public ChangeColumn(string currentName)
        {
            if (currentName.IsBlank())
                throw new ArgumentNullException("currentName");

            CurrentName = currentName;
        }

        public IChangeColumn Rename(string newName)
        {
            if(newName.IsBlank())
                throw new ArgumentNullException("newName");

            NewName = newName;
            return this;
        }

        public IChangeColumn ChangeType<TColumn>()
        {
            NewType = typeof (TColumn);
            return this;
        }

        public IChangeColumn ChangeLength(uint length)
        {
            if(length == 0)
                throw new ArgumentException("length must be greater than 0", "length");

            NewLength = length;
            return this;
        }

        public IChangeColumn AddForeignKey(string primaryKeyTable, string primaryKeyColumn)
        {
            if(primaryKeyTable.IsBlank())
                throw new ArgumentNullException("primaryKeyTable");
            if(primaryKeyColumn.IsBlank())
                throw new ArgumentNullException("primaryKeyColumn");

            NewForeignKey = ObjectFactory.With("primaryKeyTableName").EqualTo(primaryKeyTable)
                .With("primaryKeyColumnName").EqualTo(primaryKeyColumn).GetInstance<IAddForeignKey>();
            return this;
        }
    }
}
